package com.ak.config;

import com.alibaba.fastjson2.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author xk
 * @create 2023/12/7 11:27
 * @since 1.0.0
 */
@Slf4j
@Component
public class NacosRouteDefinitionRepository implements RouteDefinitionRepository {

    public final Map<String, RouteDefinition> routes = new ConcurrentHashMap<>();
    @Autowired
    private Environment environment;

    @Override
    public Flux<RouteDefinition> getRouteDefinitions() {
//        System.err.println(redisTemplate.opsForValue().get("ceshi"));
        return Flux.fromIterable(routes.values());
    }

    @Override
    public Mono<Void> save(Mono<RouteDefinition> route) {
        return route.flatMap(r -> {
            routes.put(r.getId(), r);
            return Mono.empty();
        });

    }

    @Override
    public Mono<Void> delete(Mono<String> routeId) {
        return routeId.flatMap(id -> {
            //这里加上当前模块的名称，因为routes里没有这个会报错
            if (routes.containsKey(id) || id.contains(environment.getProperty("spring.application.name"))) {
                routes.remove(id);
                log.info("路由id删除成功：{}",id);
                if(id.contains(environment.getProperty("spring.application.name"))){
                    log.warn("未找到当前服务路由id：{}",id);
                }
                return Mono.empty();
            }
            log.info("路由id删除失败：{}",id);
            return Mono.defer(() -> Mono.error(new NotFoundException("路由文件没有找到: " + routeId)));
        });
    }

    public void clear() {
        routes.clear();
    }

    private void initPredicate(RouteDefinition routeDefinition, Map<Object, Object> entries) {
        Object predicates = entries.get("predicates");
        if (predicates == null) {
            return;
        }
        JSONArray predicateArry = JSONArray.parseArray((String) predicates);
        predicateArry.parallelStream().forEach(predicate -> {
            //遍历predicates，创建RouteDefinition，并添加到RouteDefinition中
            PredicateDefinition predicateDefinition = new PredicateDefinition((String) predicate);
            routeDefinition.getPredicates().add(predicateDefinition);
        });
    }

    private void initFilter(RouteDefinition routeDefinition, Map<Object, Object> entries) {
        Object filters = entries.get("filters");
        if (filters == null) {
            return;
        }
        JSONArray predicateArry = JSONArray.parseArray((String) filters);
        predicateArry.parallelStream().forEach(filter -> {
            //遍历predicates，创建RouteDefinition，并添加到RouteDefinition中
            FilterDefinition filterDefinition = new FilterDefinition((String) filter);
            routeDefinition.getFilters().add(filterDefinition);
        });
    }

}
